package com.its.common.log;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author xiaxp
 * @Date 12/29/21 17:10
 * @Description
 */
public class LogLevelSetting implements EnvironmentPostProcessor {

    private static AtomicBoolean IN = new AtomicBoolean(false);

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        addDefaultPropertySource(environment);
    }

    private void addDefaultPropertySource(ConfigurableEnvironment environment) {
        if(IN.get()){
            return;
        }
        IN.set(true);
        HashMap<String, Object> map = new HashMap<>();
        // 自定义修改后添加进去覆盖
        MutablePropertySources sources = environment.getPropertySources();
        String activeProfiles = null;
        for (PropertySource<?> source : sources) {
            if(null != source.getProperty("spring.profiles.active")){
                activeProfiles = (String) source.getProperty("spring.profiles.active");
                break;
            }
        }

        String mybatisPlusLog = "org.apache.ibatis.logging.stdout.StdOutImpl";
        if(null != activeProfiles && (activeProfiles.contains("prd") || activeProfiles.contains("prod"))){
            //生产环境
            mybatisPlusLog = null;
        }
        if(null != mybatisPlusLog){
            map.put("mybatis-plus.configuration.log-impl", mybatisPlusLog);
            System.out.println(">>> 检测到当前环境为: 非生产环境，已打开Mybatis的SQL日志 ...");
        }

        if(null == activeProfiles){
            map.put("spring.profiles.active", "default");
        }

        if(!map.isEmpty()){
            PropertySource source = new MapPropertySource("logLevelExtend", map);
            environment.getPropertySources().addLast(source);
        }
    }
}
